package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

// 菜品控制器,完成菜品的增删改查
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;


    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("[菜品新增 distDto:{}]", dishDto);
        // 调用业务方法，完成保存
        dishService.saveWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("保存菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        log.info("[菜品的分页查询  page:{},pageSize:{},name:{}]", page, pageSize, name);


        Page<Dish> dishPage = new Page<Dish>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 3.获取到原生的分页数据
        dishService.page(dishPage, queryWrapper);

        Page<DishDto> pageDishDto = new Page<>();
        BeanUtils.copyProperties(dishPage, pageDishDto, "records");
        List<Dish> recordsDish = dishPage.getRecords();
        List<DishDto> recordsDishDto = recordsDish.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //item.getCategoryId()
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList()); // 把返回的对象，转换为一个集合对象
        pageDishDto.setRecords(recordsDishDto);
        return R.success(pageDishDto);
    }


    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id) {
        log.info("[根据ID获取菜品  id:{}]", id);
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("[更新菜品 distDto:{}]", dishDto);
        dishService.updateWithFlavor(dishDto);
        String keys = "dish_*";
        redisTemplate.delete(keys);

        return R.success("更新成功");
    }


    @Autowired
    private DishFlavorService dishFlavorService;

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> redisDishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        redisDishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (redisDishDtoList != null) {
            log.info("[从redis,读取分类下的菜品 key:{}]", key);
            log.info("[redis内容:{}]", Arrays.toString(redisDishDtoList.toArray()));
            return R.success(redisDishDtoList);
        }
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
